package utils

import (
	"fmt"
	"time"

	"github.com/dgrijalva/jwt-go"
)

var jwtSecretKey = []byte("MyJwtSecretKey123!@#")

type UserClaim struct {
	UserID    uint64 `json:"user_id"`
	UserName  string `json:"user_name"`
	UserEmail string `json:"user_email"`
	jwt.StandardClaims
}

func GenerateToken(userID uint64, userName string, userEmail string) (string, error) {
	// 设置token有效期，例如24小时
	expireTime := time.Now().Add(24 * time.Hour)

	//创建token结构体
	claim := UserClaim{
		userID,
		userName,
		userEmail,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    "test",
		},
	}

	// 创建一个新的token对象，指定签名方法和声明
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	tokenString, err := token.SignedString(jwtSecretKey)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

func ValidateToken(cookie string) (*UserClaim, error) {
	claim := UserClaim{}
	token, err := jwt.ParseWithClaims(cookie, &claim, func(token *jwt.Token) (interface{}, error) {
		// 确保 token 方法为 HMAC
		_, ok := token.Method.(*jwt.SigningMethodHMAC)
		if !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		// 返回密钥
		return []byte("MyJwtSecretKey123!@#"), nil
	})
	if err != nil {
		return nil, err
	}
	claims, ok := token.Claims.(*UserClaim)
	if ok && token.Valid {
		return claims, nil
	} else {
		return nil, fmt.Errorf("claims转换UserClaims失败")
	}
}
